package com.smartlink.app.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.smartlink.app.R;
import com.smartlink.app.activity.BluetoothActivity;
import com.smartlink.app.common.Constant;
import com.smartlink.app.dialog.WaitDialog;
import com.smartlink.app.face.OnlineFaceDemo;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;


public class StudentFragment extends Fragment implements View.OnClickListener {

    private Button btn_student_sign;
    private TextView tv_student_className;
    private TextView tv_student_state;
    private SharedPreferences sharedPreferences;
    private WaitDialog waitDialog;
    private Button btn_student_refresh;
    private String classRoomId;
    private boolean havaClassRoomId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_student, container, false);
        sharedPreferences = getActivity().getSharedPreferences("main", Context.MODE_PRIVATE);
        btn_student_refresh = (Button) view.findViewById(R.id.btn_student_refresh);
        btn_student_sign = (Button) view.findViewById(R.id.btn_student_sign);
        btn_student_sign.setOnClickListener(this);
        tv_student_className = (TextView) view.findViewById(R.id.tv_student_className);
        tv_student_state = (TextView) view.findViewById(R.id.tv_student_state);
        btn_student_refresh.setOnClickListener(this);
        //检查是否存在教室id
        checkClassRoomId();
        return view;
    }

    @Override
    public void onResume() {
        if (havaClassRoomId) {
            String classRoomName = sharedPreferences.getString("classRoomName", "");
            tv_student_className.setText(classRoomName);
            getSignInState();
        } else {
            tv_student_className.setText("无法获取所在教室");
            btn_student_sign.setEnabled(false);
            btn_student_refresh.setEnabled(false);
        }
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_student_sign:
                Intent intent = new Intent(getActivity(), OnlineFaceDemo.class);
                startActivity(intent);
                break;
            case R.id.btn_student_refresh:
                getSignInState();
                break;
        }
    }

    /**
     * 初始化界面
     *
     * @param signInState
     */
    public void initView(String signInState) {
        btn_student_sign.setEnabled(true);
        btn_student_refresh.setEnabled(true);

        tv_student_state.setText(signInState);
        if ("已签到".equals(signInState)) {
            btn_student_sign.setEnabled(false);
        }
        //取消加载对话框
        waitDialog.dismiss();
    }

    /**
     * 获取学生签到状态
     */
    public void getSignInState() {
        //显示加载对话框
        waitDialog = WaitDialog.getWaitDialog(getContext());
        String studentNumber = sharedPreferences.getString("number", "13114120114");
        String classroomId = sharedPreferences.getString("classRoomId", "");
        String ip = sharedPreferences.getString("ip", Constant.HTTP.HTTP_PORT);
        String path = "http://" + ip + ":8080/smartlink/isSignIn?number=" + studentNumber;
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.get(path, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                String body = new String(bytes);
                try {
                    JSONObject jsonObject = new JSONObject(body);
                    boolean isSignIn = jsonObject.getBoolean("result");
                    String signInState = "";
                    if (isSignIn) {
                        signInState = "已签到";
                    } else {
                        signInState = "未签到";
                    }
                    initView(signInState);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });
    }

    /**
     * 判断是否存在教室Id
     */
    private void checkClassRoomId() {
        //判断是否有教室ID
        classRoomId = sharedPreferences.getString("classRoomId", "");
        if (classRoomId.equals("")) {
            Intent intent = new Intent(getContext(), BluetoothActivity.class);
            startActivityForResult(intent, 0x111);
        } else {
            havaClassRoomId = true;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0x111) {
            if (resultCode == BluetoothActivity.RESULT_SUCCESS) {
                havaClassRoomId = true;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
